package material

import (
	"context"
	"fmt"
	"gitee.com/bobo-rs/idea-space-framework/framework/dao"
	"gitee.com/bobo-rs/idea-space-framework/framework/model"
	"github.com/gogf/gf/v2/frame/g"
)

// GetMaterialTemplateList 获取素材模板列表
func (m *sMaterial) GetMaterialTemplateList(ctx context.Context, in model.MaterialTemplateListInput) (out *model.MaterialTemplateListOutput, err error) {
	out = &model.MaterialTemplateListOutput{}
	// 查询数据列表
	err = m.ProcessMaterialTemplateListAndTotal(
		ctx,
		model.CommonListAndTotalInput{
			CommonPaginationItem: in.CommonPaginationItem,
			Where:                m.FormatMaterialTemplateWhere(ctx, in.MaterialTemplateListWhereItem),
			Sort: fmt.Sprintf(
				`%s desc, %s desc, %s desc`,
				dao.MaterialTemplate.Columns().UseNum,
				dao.MaterialTemplate.Columns().MatchNum,
				dao.MaterialTemplate.Columns().Id,
			),
		},
		&out.Rows,
		&out.Total,
	)
	if err != nil {
		return nil, err
	}
	// 未获取到数据
	if len(out.Rows) == 0 {
		return
	}
	// 处理数据
	for key, row := range out.Rows {
		m.FormatMaterialTemplateDetail(&row)
		out.Rows[key] = row
	}
	return
}

// GetMaterialTemplateDetail 获取素材模板详情
func (m *sMaterial) GetMaterialTemplateDetail(ctx context.Context, tid uint) (out *model.MaterialTemplateDetailOutput, err error) {
	out = &model.MaterialTemplateDetailOutput{}
	// 获取数据
	err = m.ProcessMaterialTemplateDetailById(
		ctx, tid, &out.MaterialTemplateDetailItem,
	)
	if err != nil {
		return nil, err
	}
	// 格式化数据
	m.FormatMaterialTemplateDetail(&out.MaterialTemplateItem)
	// 素材文案列表
	var words []model.MaterialTemplateWordsDetailItem
	words, _ = m.ProcessTemplateWordsWithList(
		ctx, g.Map{dao.MaterialTemplateWords.Columns().TemplateId: tid},
	)
	// 处理数据
	out.MaterialTemplateDetailItem.Words = words
	return
}
